<?php
if(!isset($_SESSION)) session_start();
require_once("dbclass.php");

class login {
   private $status=0;  //0 - none, 1 - invalid login, 2 - successfull login
   public $db;
   private $user_data = array("user"=>"","pass"=>"","current_url"=>"index.php");
   
   public function verifyStr($str) {
       if(preg_match('/^[0-9A-Za-z\._ ]*$/', $str)) return true;
       else return false;
   }

   public function getStatus() {
       return $this->status;
   }

   public function connectToDb() {
        $this->db = new dbclass;
        $parameters = array("localhost:3306","root","expedia");
        $this->db->connect($parameters)->select_db("eandb");
   }

   public function getPost() {
       $arrPost = array("user","pass","current_url");
       $arrVerify = array("user","pass");

       if(count($_POST)>0) {
          $this->status = 1;
          foreach($arrPost as $value) {
              if(isset($_POST[$value])) {
                  if(in_array($value, $arrVerify) && $this->verifyStr($_POST[$value])) {
                      $this->user_data[$value] = $_POST[$value];
                  }
                  if(!in_array($value, $arrVerify))
                      $this->user_data[$value] = $_POST[$value];
              }
          }
       } else $this->status = 0;
    }

    public function getUserData() {
        return $this->user_data;
    }

    public function checkIfValid() {
        if($this->user_data["user"]!="" && $this->user_data["pass"]!="") {
            $result = $this->db->query("SELECT * FROM users WHERE username = '".$this->user_data["user"]."'
                              AND password = '".sha1("xw".$this->user_data["pass"])."'")->fetch();
            if($result && count($result)>0) {
                $_SESSION["logged_user"] = $result[0]["username"];
                $_SESSION["logged_bool"] = true;
                $this->status = 2;
            } else {
                $this->status = 1;
                $_SESSION['loginFail'] = TRUE;
            }
        } elseif (isset($_POST['user']) && isset($_POST['pass'])) {
            $_SESSION['loginFail'] = TRUE;
        }
    }

    public function redirect() {
        header("Location:".$this->user_data["current_url"]);
    }
}

$login = new login;
$login->connectToDb();
$login->getPost();
$login->checkIfValid();

//$login->redirect();

?>
